<template>
  <el-dialog
    v-model="loginVisible"
    width="460px"
    :close-on-click-modal="false"
    :show-close="true"
    destroy-on-close
    class="login-dialog"
  >
    <login-modal v-model="loginVisible" />
  </el-dialog>
  <div v-if="flag">
    <div class="welcome-message" v-if="messages.length === 0">
      <!-- 修正：将logo和文字放在同一行的容器 -->
      <div style="display: flex; align-items: center; justify-content: center">
        <!-- 新增justify-content: center -->
        <!-- <img src="@/assets/logo/logo.png" alt="潍小智Logo" class="welcome-logo" /> -->
        <h1 class="gradient-text text-2xl">匿名聊天,保护隐私</h1>
      </div>
    </div>

    <!-- 底部工具栏 -->
    <div class="bottom-toolbar1">
      <!-- 输入区域 -->
      
        <div class="input-container1">
          <textarea
            v-model="inputValue"
            type="text"
            placeholder="给潍小智发送信息,聊天不会记录个人信息!"
            @keyup.enter="startStream"
          />
          <button @click="startStream">
            <span>发送</span>
          </button>
        </div>
    </div>
  </div>
  <div class="chat-box" v-else>
    <!-- 聊天内容显示区域 -->
    <div class="chat-content" ref="chatContent">
      <!-- 首次进入显示欢迎信息 -->

      <!-- 消息列表 -->
      <div class="messages">
        <template v-for="(message, index) in messages">
          <!-- 用户消息气泡 -->
          <div
            v-if="message.type === 'user'"
            :key="'user-' + index"
            class="message-wrapper user"
          >
            <div
              class="message user-message"
              v-html="markdownToHtml(message.content)"
            ></div>
          </div>
          <!-- AI消息气泡 -->
          <div v-else :key="'ai-' + index" class="message-wrapper ai">
            <div
              class="message ai-message"
              v-html="markdownToHtml(message.content)"
            ></div>
          </div>
        </template>
      </div>
    </div>

    <!-- 底部工具栏 -->
    <div class="bottom-toolbar">
      <!-- 输入区域 -->
      <div class="input-footer">
        <div class="input-container">
          <input
            v-model="inputValue"
            type="text"
            :placeholder="
              isLoading ? '正在回复中...' : '请输入你的问题吧,我可以给予你帮助'
            "
            @keyup.enter="startStreamConnection"
            :disabled="isLoading"
          />
          <button @click="startStreamConnection">
            <span>发送</span>
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { defineExpose, nextTick, onBeforeUnmount, ref, watch, defineModel } from "vue";
import { marked } from "marked"; // markdown解析器
import { ElMessage } from "element-plus"; // Element Plus的消息提示组件
//import { useUserStore } from '@/stores/user' // 获取token的工具函数
import { useChatStore } from "@/store/modules/chat";
import { saveHistory, askAliyunStream } from "@/api/chat";
import { useUserStore } from "@/store/modules/user";
const isflag = defineModel();
const userStore = useUserStore();
const chatStore = useChatStore();
// 聊天消息列表
const messages = ref([]);
// 输入框的值
const inputValue = ref("");
// 事件源对象,用于SSE连接
const eventSource = ref(null);
//用于存储当前正在累积的markdown文本
const currentMarkdownBuffer = ref("");
// 聊天内容区域的DOM引用
const chatContent = ref(null);
// 加载状态标志
const isLoading = ref(false);
const loginVisible = ref(false);
const flag = isflag;
// 重置聊天功能
const resetChat = () => {
  console.log("执行重置操作");
  // 清空消息列表,触发欢迎界面显示
  messages.value = [];
  // 关闭流式连接
  if (eventSource.value) {
    eventSource.value.close();
    eventSource.value = null;
  }
  // 清空输入框和缓冲区
  inputValue.value = "";
  currentMarkdownBuffer.value = "";
  // 确保滚动到顶部并重新渲染欢迎界面
  nextTick(() => {
    if (chatContent.value) {
      chatContent.value.scrollTop = 0;
    }
  });
  // 创建新的对话ID
  chatStore.createNewChat();
  console.log("新的对话ID已创建:", chatStore.currentChatId);
};
// 将Markdown文本转换为HTML
const markdownToHtml = (content) => {
  return marked(content || "");
};
// 滚动到聊天区域底部
const scrollToBottom = () => {
  nextTick(() => {
    if (chatContent.value) {
      chatContent.value.scrollTop = chatContent.value.scrollHeight;
    }
  });
};
// 在 setup 中添加
const loadHistoryMessages = (historyMessages) => {
  // 清空当前消息
  messages.value = [];
  // 加载历史消息
  historyMessages.forEach((msg) => {
    messages.value.push(
      { type: "user", content: msg.ask },
      { type: "assistant", content: msg.request }
    );
  });
};
function startStream() {
  console.log("flag" + flag.value);
  if (!userStore.token) {
    ElMessage.error("请登录后使用功能!");
    return;
  }
  if (inputValue.value.trim() == "") {
    ElMessage.error("请输入问题");
    return;
  }
  flag.value = false;
  console.log("flag" + flag.value);
  startStreamConnection();
}

// 修改开始流式连接的方法
const startStreamConnection = async () => {
  if (!userStore.token) {
    ElMessage.error("请登录后使用功能!");
    return;
  }
  try {
    isLoading.value = true;
    if (!inputValue.value.trim()) return;
    const token = userStore.token;
    console.log("token" + token);
    // 每次发送消息前重新获取用户ID
    const currentUserId = userStore.id;
    console.log("当前用户的id为" + currentUserId);
    // 如果没有当前对话ID，创建新的
    if (!chatStore.currentChatId) {
      chatStore.createNewChat();
    }
    const userMessage = inputValue.value;
    // 添加用户消息到消息列表
    messages.value.push({
      type: "user",
      content: userMessage,
    });
    // 准备历史记录数据
    const historyData = {
      userId: null,
      chatId: "private",
      ask: userMessage,
      request: "", // AI的回答会在流结束后更新
      time: new Date().toISOString().replace("T", " ").split(".")[0],
    };
    console.log("historyData.ask为" + historyData.ask);
    console.log("historyData.request为" + historyData.request);
    // 清空输入框
    inputValue.value = "";

    // 使用API函数获取流式响应
    const response = await askAliyunStream(userMessage, token);

    console.log("response为" + response);
    // 检查响应状态
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    // 获取响应流的读取器
    const reader = response.body?.getReader();
    if (!reader) {
      throw new Error("Reader not available");
    }

    // 用于解码和存储响应数据
    const decoder = new TextDecoder();
    // let buffer = ''
    console.log("开始循环读取流数据");
    // 循环读取流数据
    while (true) {
      const { done, value } = await reader.read();
      console.log("done为" + done);
      console.log("value为" + value);
      if (done) break;
      // 解码新的数据块
      const text = decoder.decode(value, { stream: true });
      console.log("text为" + text);

      // 检查是否收到结束标记
      if (text.includes("[DONE]")) {
        break;
      }

      // 处理接收到的消息
      if (!currentMarkdownBuffer.value) {
        // 如果是第一条消息,创建新的AI回复
        messages.value.push({
          type: "ai",
          content: text,
        });
      } else {
        // 更新最后一条AI消息
        messages.value[messages.value.length - 1].content =
          currentMarkdownBuffer.value + text;
      }

      // 累积消息内容
      currentMarkdownBuffer.value += text;
      // 滚动到底部
      scrollToBottom();
    }
    console.log("currentMarkdownBuffer.value为" + currentMarkdownBuffer.value);

    // 在接收完整个回答后，更新历史记录
    historyData.request = currentMarkdownBuffer.value;
    console.log("historyData.request为" + historyData.request);
    console.log("historyData:" + historyData);
    // 等待后端保存成功
    await saveHistory(historyData);

    // 延迟一小段时间后再获取最新列表，确保后端数据已更新
    setTimeout(async () => {
      await chatStore.fetchHistoryList();
    }, 100);
  } catch (error) {
    console.error("Stream error:", error);
    ElMessage.error("连接出错，请重试");
  } finally {
    isLoading.value = false;
    currentMarkdownBuffer.value = "";
  }
};

// 组件卸载前清理工作
onBeforeUnmount(() => {
  if (eventSource.value) {
    eventSource.value.close();
  }
});

// 暴露方法给父组件
defineExpose({
  resetChat,
  loadHistoryMessages,
});
</script>

<style scoped>
.chat-box {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
}

.chat-content {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  position: relative;
}

.welcome-message {
  margin-top: 150px;
  text-align: center;
}

.welcome-message h1.gradient-text {
  background: linear-gradient(to right, #8a9396, #3d4347, #747d80);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent !important;
  font-weight: bold;
  animation: gradient 3s ease infinite;
  background-size: 200% auto;
  margin-bottom: 20px;
}

.welcome-message p.gradient-text {
  background: linear-gradient(to right, #2193b0, #3498db, #6dd5ed);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent !important;
  font-weight: bold;
  animation: gradient 3s ease infinite;
  background-size: 200% auto;
}

.welcome-message h1 {
  font-size: 4.5em;
  margin-bottom: 20px;
}

.welcome-message p {
  font-size: 1.5em;
}

.bottom-toolbar {
  position: sticky;
  bottom: 0;

  border-top: 1px solid #e8e8e8;
  padding: 10px 20px;
  z-index: 10;
}
.bottom-toolbar1 {
  /* 居中 */

  /* width: 100%;
  position: relative; */
  left: 4%;
  transform: translate(0%, 0%);
  height: 200px;

  bottom: 0;
  padding: 10px 20px;
  z-index: 10;
}
.tool-buttons {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
}

.tool-btn {
  padding: 8px;
  border: none;
  background: none;
  cursor: pointer;
  border-radius: 4px;
}

.tool-btn:hover {
  background-color: #f5f5f5;
}

.input-container {
  display: flex;
  gap: 10px;
  background-color: white;
  padding: 10px;
  border-radius: 8px;
}
.input-container1 {
  position: relative;

  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px;
  padding: 10px;
  border-radius: 8px;
}
.input-container1 textarea {
  position: relative;
  width: 70%;
  height: 10rem;
  padding: 12px;
  border-radius: 8px;
  font-size: 14px;
  resize: none;
}
.input-container1 button {
  position: absolute;
  right: 16.5%;
  bottom: 10%;
  width: 100px;
  height: 50px;
  padding: 12px 24px;
  background-color: #4e6ef2;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
}
.input-container input {
  flex: 1;
  padding: 12px;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  font-size: 14px;
}

.input-container button {
  padding: 12px 24px;
  background-color: #4e6ef2;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
}

.message-wrapper {
  display: flex;
  margin: 20px 0;
}

.message-wrapper.user {
  justify-content: flex-end;
}

.message {
  max-width: 80%;
  padding: 0px 16px;
  border-radius: 12px;
  font-size: 14px;
  line-height: 1.5;
}

.user-message {
  background-color: #4e6ef2;
  color: white;
}

.ai-message {
  background-color: #f5f5f5;
  color: #333;
}

.chat-content::-webkit-scrollbar {
  width: 6px;
}

.chat-content::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.chat-content::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 3px;
}

.chat-content::-webkit-scrollbar-thumb:hover {
  background: #555;
}

:deep(.login-dialog) {
  border-radius: 8px;
}

:deep(.login-dialog .el-dialog__header) {
  margin: 0;
  padding: 20px 30px;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.login-dialog .el-dialog__body) {
  padding: 0;
}

:deep(.login-dialog .el-dialog__headerbtn) {
  top: 20px;
  right: 20px;
}

@keyframes gradient {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}

.welcome-logo {
  width: 70px; /* 减小logo尺寸，使其更适合与文字对齐 */
  height: 70px;
  margin-bottom: 0; /* 移除底部边距 */
  object-fit: contain;
}
@media screen and (max-width: 768px) {
  .welcome-logo{
    display: none;
  }
  .welcome-message h1 {
  font-size: 7rem;
  margin-bottom: 20px;
}
.input-container1 textarea {
  position: relative;
  width: 90%;
  height: 40rem;
  padding: 12px;
  border-radius: 8px;
  font-size: 14px;
  resize: none;
}
.input-container1 button {
  position: absolute;
  right: 9%;
  bottom: 11%;
  width: 70px;
  height: 40px;
  padding: 6px 12px;
  background-color: #4e6ef2;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
}
 }
</style>
